#include "fastcgi.hxx"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory.h>
#include <iostream>

using namespace webby;

int main()
{
	FastCGI f;

	int s = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
	socklen_t i = 64*1024;
//	setsockopt( s, SOL_SOCKET, SO_RCVBUF, &i, sizeof(i));
	sockaddr_in addr;
	memset( &addr, 0, sizeof(addr) );
	addr.sin_port = htons( 2000 );
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr("127.0.0.1");

	if ( connect(s,(sockaddr *)& addr, sizeof(addr) ) != -1 ) 
	{
		std::cout << "Connected" << std::endl;
	}

	fd_set read_set;
	FD_ZERO( &read_set );
	FD_SET( s, &read_set );

	f.makeBeginRequest();
	send( s, f.mBuffer, 16, 0 );
	f.encodeParam( "SCRIPT_FILENAME", "/var/www/html/duanestorey.com/index.php" );
	unsigned int l = f.mBuffer[5] + 8;

	std::cout << std::endl;
	for (unsigned int i = 0 ; i < l; i++)
	{
		char s[10];
		sprintf(s, "%c ", f.mBuffer[i]);
		std::cout << s;
	}	
	std::cout << std::endl;

	send(s, f.mBuffer, l, 0);

	f.encodeParam( "", "" );
	l = f.mBuffer[5] + 8;	
	send(s, f.mBuffer, l, 0);
	f.makeStdIn();
	l = f.mBuffer[5] + 8;	
	send(s, f.mBuffer, l, 0);
	
	timeval tv;
	tv.tv_sec = 1;
	tv.tv_usec = 0;
	select( s + 1, &read_set, 0, 0, &tv );

	char c[1024*64];

	for (unsigned int i = 0 ; i < 16; i++)
	{
		char s[10];
		sprintf(s, "%02x ", f.mBuffer[i]);
		std::cout << s;
	}	
	std::cout << std::endl;

	if ( FD_ISSET( s, &read_set ) )
	{
		int i = recv( s, c, 1024*64, 0 );
		std::cout << "Can read " << i << std::endl;
		c[i] = 0;
//		std::cout << &c[8];
	}
	return 0;
}
